package com.xiaobai.auth.config;


import com.xiaobai.common.utils.tool.Safes;
import com.xiaobai.data.manager.system.ApiAuthorityManager;
import com.xiaobai.data.manager.system.MenuManager;
import com.xiaobai.data.manager.system.RoleApiManager;
import com.xiaobai.data.manager.system.RoleManager;
import com.xiaobai.data.manager.system.RoleMenuManager;
import com.xiaobai.data.manager.system.UserManager;
import com.xiaobai.model.entity.system.User;
import com.xiaobai.model.vo.system.apiAuthority.ApiAuthorityTreeVO;
import com.xiaobai.model.vo.system.login.LoginUser;
import jakarta.annotation.Resource;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 自定义UserDetailsService 用于认证和授权
 * 此处把用户的信息和权限交给spring security
 * spring security会对用户的信息和权限信息进行管理
 * @author hffan
 * serDetailService接口主要定义了一个方法 l
 * oadUserByUsername(String username)用于完成用户信息的查询，
 * 其中username就是登录时的登录名称，登录认证时，需要自定义一个实现类实现UserDetailService接口，
 * 完成数据库查询，该接口返回UserDetail。
 */
@Component("customerUserDetailsService")
public class CustomerUserDetailsService implements UserDetailsService {
    @Resource
    private UserManager userManager;
    @Resource
    private MenuManager menuManager;
    @Resource
    private RoleManager roleManager;
    @Resource
    private RoleMenuManager roleMenuManager;
    @Resource
    private ApiAuthorityManager apiAuthorityManager;
    @Resource
    private RoleApiManager roleApiManager;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = userManager.getUserInfoByUserId(username);
        // 如果用户不存在
        if (user == null){
            throw new UsernameNotFoundException("用户名或者密码错误");
        }
        //这儿还差一个角色添加
        //配置权限值
        List<ApiAuthorityTreeVO> apiAuthorityTreeVOList = apiAuthorityManager.getApiAuthorityByUserId(user.getId());
        List<String> authorityList = Safes.of(apiAuthorityTreeVOList).stream().map(ApiAuthorityTreeVO::getApiValue).collect(Collectors.toList());
        // 授权
        return new LoginUser(authorityList, user);
    }
}
